package com.mingtu.jgspatrol.fragment;

import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.activity.ParkReserveDetailActivity;
import com.mingtu.jgspatrol.adapter.ParkReserveAdapter;
import com.mingtu.jgspatrol.bean.ParkAuditBean;
import com.mingtu.jgspatrol.databinding.FragmentParkAuditBinding;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;

public class ParkAuditFragment extends BaseBindingFragment<FragmentParkAuditBinding> implements LazyFragmentPagerAdapter.Laziable {
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private ParkReserveAdapter parkAuditAdapter;

    private int status;
    private static final String ARG_PARAM1 = "param1";
    private String plateNo = null;
    private String beginDate = null;
    private String endDate = null;
    private TextView textView;
    private int totalCount;

    private int PAGE_SIZE = 10;


    public static ParkAuditFragment getInstance(int status, TextView textView) {
        ParkAuditFragment ef = new ParkAuditFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ARG_PARAM1, status);
        ef.setArguments(bundle);
        ef.textView = textView;
        return ef;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            status = getArguments().getInt(ARG_PARAM1);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_park_audit;
    }

    @Override
    protected void initData() {


    }


    @Override
    protected void initView() {
        LinearLayoutManager manager = new LinearLayoutManager(context);
        binding.recycler.setLayoutManager(manager);
        binding.recycler.addItemDecoration(new BottomSpaceItemDecoration());

        parkAuditAdapter = new ParkReserveAdapter();
        if (isOpenLoadAnimation) {
            parkAuditAdapter.isFirstOnly(isFirstOnly);
            parkAuditAdapter.openLoadAnimation(animationType);
        }
        parkAuditAdapter.setEmptyView(new EmptyDataLayout(context));
        binding.recycler.setAdapter(parkAuditAdapter);
        parkAuditAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                ParkAuditBean.PageBean.ListBean listBean = parkAuditAdapter.getData().get(i);
                int id = listBean.getId();
                Bundle bundle = new Bundle();
                bundle.putInt("id", id);
                IntentUtils.getInstance().readyGo(getActivity(), ParkReserveDetailActivity.class, bundle);
            }
        });

        binding.topLayout.editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH || i == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    //此处做逻辑处理
                    plateNo = UIUtils.getTextView(textView);
                    getListData(1);
                    return true;
                }
                return false;
            }
        });

        binding.topLayout.ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                plateNo = UIUtils.getTextView(binding.topLayout.editText);
                getListData(1);
            }
        });


    }

    @Override
    protected void getData() {
        getListData(1);
        initListener();
    }


    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                getListData(1);
            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(parkAuditAdapter.getData(), PAGE_SIZE);
                    getListData(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 审核列表
     */
    public void getListData(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", PAGE_SIZE);
        hashMap.put("status", status);
        hashMap.put("beginDate", beginDate);
        hashMap.put("endDate", endDate);
        hashMap.put("plateNo", plateNo);
        MyUtills.removeMapNull(hashMap); //去除空对象
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_RESERVATION_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            ParkAuditBean parkAuditBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                parkAuditBean = new ParkAuditBean();
                                parkAuditBean = gson.fromJson(result, ParkAuditBean.class);
                                ParkAuditBean.PageBean pageBean = parkAuditBean.getPage();
                                List<ParkAuditBean.PageBean.ListBean> dataBeans = pageBean.getList();
                                totalCount = pageBean.getTotalCount();
                                textView.setText("（" + totalCount + "）");

                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            parkAuditAdapter.replaceData(dataBeans);
                                        } else {
                                            parkAuditAdapter.addData(dataBeans);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));

                            }

                        }
                    }
                });

    }


    public void getCurrentAuditData(String currentTime) {
        this.beginDate = currentTime;
        this.endDate = currentTime;
        getListData(1);
    }

    /**
     * 在顶部添加数据
     *
     * @param listBean
     */
    public void addData(ParkAuditBean.PageBean.ListBean listBean) {
        parkAuditAdapter.addData(0, listBean);
        textView.setText("（" + (totalCount + 1) + "）");
    }

    /**
     * 删除数据
     *
     * @param position
     */
    public void removeData(int position) {
        parkAuditAdapter.remove(position);
        textView.setText("（" + (totalCount - 1) + "）");
    }

}